//
//  XQViewController.m
//  7.14详情
//
//  Created by lovena on 15/7/15.
//  Copyright (c) 2015年 lovena. All rights reserved.
//

#import "XQViewController.h"
#import "XQHeaderView.h"
#import "XQFooterView.h"
#import "SECViewController.h"
#import "MJExtension.h"
#import "MJExtension.h"
#import "XQCellModel.h"
#import "PJCell.h"
#import "UIViewExt.h"
#import "CharTableViewController.h"
#import "DSZMainViewController.h"
#import "Common.h"
#import "AddToBuyView.h"
#import "DSZShopViewController.h"
#import "DSZShopViewController.h"
#import "DSZShopDetailViewController.h"
#import "MJChiBaoZiHeader.h"
#import "MBProgressHUD.h"
#import "MBProgressHUD+MJ.h"
#import "UMSocial.h"
#import "UMSocialSinaHandler.h"
#import "DSZLoginViewController.h"
@interface XQViewController ()<UIGestureRecognizerDelegate>
@property(nonatomic,strong)NSArray *array;//数组
@property(nonatomic,assign)CGFloat cellHeight;
@property(nonatomic,retain)XQFooterView *footView;
@property(nonatomic,assign)BOOL isclick;//判断是否点击尾部
@property(nonatomic,retain)DSZMainViewController *main;
@end

@implementation XQViewController
//隐藏状态栏和导航栏
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    DSZMainViewController *con = (DSZMainViewController*)self.tabBarController;
    [con hiddenMainTabbar:YES];
     //把导航栏放到表的上面
    [self.view bringSubviewToFront:self.QXnaView];
    //把背景视图放到最上面
    [self.view bringSubviewToFront:_backGroundVie];
    //把三个按钮放在背景视图上
    [self.view insertSubview:self.homeView aboveSubview:_backGroundVie];
    [self.view insertSubview:self.shareView aboveSubview:_backGroundVie];
    [self.view insertSubview:self.refreshView aboveSubview:_backGroundVie];
    //添加遮罩
    self.maskView = [[UIView alloc]initWithFrame:self.view.bounds];
    _maskView.backgroundColor = [UIColor grayColor];
    _maskView.alpha = 1;
    [self.view addSubview:_maskView];
    self.maskView.hidden = YES;
    //给遮罩添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeMask)];
    [self.maskView addGestureRecognizer:tap];
    //添加添加到购物车视图
    _buyView = [AddToBuyView createView];
    _buyView.top = 480;
    _buyView.delegate = self;
    [_buyView setData:self.model];
    [self.maskView addSubview:_buyView];
    //读档，判断当前购物车里是否有物品，没有让徽章隐藏，有让徽章显示物品数
    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:FilePath];
    int cou = array.count;//此处的cou是文件里的模型的数量，但是每个模型里的count代表这个商品购买的数量
    if (cou==0) {
        _huizhang.hidden = YES;
    }
    else
    {
        int a = 0;
        for (ShopModel *model in array) {
            a  = a + model.count;
        }
        _huizhang.hidden = NO;
        //改变徽章数
        NSString *str = [NSString stringWithFormat:@"%d",a];
        [_huizhang setTitle:str forState:UIControlStateNormal];

    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
}
-(void)viewDidAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //隐藏导航栏
    self.navigationController.navigationBarHidden=NO;
    
    //购物按钮的裁剪
    _buyBtn.layer.cornerRadius=5;
    _buyBtn.layer.masksToBounds=YES;
    
    _addTUBuyBtn.layer.cornerRadius=5;
    _addTUBuyBtn.layer.masksToBounds=YES;
    //徽章按钮的裁剪
    _huizhang.layer.cornerRadius = 10;
    _huizhang.layer.masksToBounds = YES;
    self.tableView.backgroundColor=[UIColor blackColor];
    XQHeaderView *header=[XQHeaderView initWithHeader];
    header.delegate=self;
    [header setModel:self.model];
    [header setData];
    self.tableView.tableHeaderView=header;
    self.tableView.bounces=NO;
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    _footView=[XQFooterView initWithFooter];
    self.tableView.tableFooterView=_footView;
    

    //添加手势
    UISwipeGestureRecognizer *swipe=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(gotoNext)];
    //向上划
    swipe.direction=UISwipeGestureRecognizerDirectionUp ;
    [self.tableView addGestureRecognizer:swipe];
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickFoot:)];
    [self.tableView addGestureRecognizer:tap];
    //根据传过来的模型给购物车模型赋值
    _shopModel.icon = _model.image[0];
    _shopModel.name = _model.name;
    _shopModel.count = 1;
    _shopModel.price = _model.price;
    _shopModel.oldprice = _model.oldprice;
    _shopModel.type = _model.type;
    _shopModel.flag = YES;
}


//数据加载
-(NSArray *)array
{
    if(_array==nil)
    {
        _array=[NSArray array];
        _array=[XQCellModel modelArrayWithFilename:@"pj.plist"];
    }
    return _array;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID=@"cell";
    PJCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    if(cell==nil)
    {
        cell=[[PJCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.cmodel=self.array[indexPath.row];
    _cellHeight=cell.cellHeight;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return _cellHeight;
}

//代理
-(void)clickDetail
{
    self.QXnaView.hidden = YES;
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SECViewController *vc=[story instantiateViewControllerWithIdentifier:@"detail"];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)hiddenNav:(BOOL)flag
{
    self.navigationController.navigationBarHidden=flag;
    if (flag==YES) {
         _blackView.frame=CGRectMake(0, 480, 320, 44);
        CGRect frame = self.QXnaView.frame;
        frame.origin.y = -64;
        self.QXnaView.frame = frame;

    }
   else
   {
       _blackView.frame=CGRectMake(0, 436, 320, 44);
       CGRect frame = self.QXnaView.frame;
       self.navigationController.navigationBarHidden =YES;
       frame.origin.y = 0;
       self.QXnaView.frame = frame;
   }
}

//调出下一页
//支持多个手势
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

-(void)clickFoot:(UITapGestureRecognizer *)tap
{
    CGPoint point=[tap locationInView:self.view];
    if (CGRectContainsPoint(self.footView.frame, point)) {
        _isclick=YES;
       
    }
    else
    {
        _isclick=NO;
    }
    }

-(void)gotoNext
{
    if(_isclick==YES)
    {
        UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        SECViewController *vc=[story instantiateViewControllerWithIdentifier:@"detail"];
        [self.navigationController pushViewController:vc animated:YES];
    }   

}
/***************************自己填写**************************/
//购买按钮
- (IBAction)butBtnClick {
    NSString *name;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    name=[defaults objectForKey:@"zh2"];
    if ([name isEqualToString:@"disizu"]) {
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"ShopDetailStory" bundle:nil];
        DSZShopDetailViewController *shop = [story instantiateViewControllerWithIdentifier:@"showdetail"];
        //[self presentViewController:shop animated:YES completion:nil];
        [self.navigationController pushViewController:shop animated:YES];
    }
    else
    {
        DSZLoginViewController *con = [[DSZLoginViewController alloc]init];
        [self.navigationController pushViewController:con animated:YES];
    }
  
}


//加入购物车按钮
- (IBAction)addToBuyBtnClick {
    NSString *name;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    name=[defaults objectForKey:@"zh2"];
    if ([name isEqualToString:@"disizu"]) {
        self.maskView.hidden = NO;
        self.buyView.bottom = 480;
    }
    else
    {
        DSZLoginViewController *con = [[DSZLoginViewController alloc]init];
        [self.navigationController pushViewController:con animated:YES];
    }

    
   
  

    
}
//调入购物车按钮
- (IBAction)gotoBtn {
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    DSZShopViewController *vc=[story instantiateViewControllerWithIdentifier:@"shop"];
   
    [self.navigationController pushViewController:vc animated:YES];
    
    _main=(DSZMainViewController *)self.tabBarController;
    [_main hiddenMainTabbar:YES];
    
}


//人工服务
- (IBAction)gotoKnowBtn {
    
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"XQ" bundle:nil];
    CharTableViewController *vc=[story instantiateViewControllerWithIdentifier:@"char"];
    [self.navigationController pushViewController:vc animated:YES];
}



- (IBAction)returnClick {
    [self.navigationController popViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"displayTabBar" object:nil];
}
- (IBAction)favoriteClick {
    if (_favoriteView.selected == NO) {
        _favoriteView.selected = YES;
    }
    else
    {
        _favoriteView.selected = NO;
    }
}
- (IBAction)moreClick {
    if (_backGroundVie.hidden) {
        _backGroundVie.hidden = NO;
        _homeView.hidden = NO;
        _refreshView.hidden = NO;
        _shareView.hidden = NO;
    }
    else
    {
        _backGroundVie.hidden = YES;
        _homeView.hidden = YES;
        _refreshView.hidden = YES;
        _shareView.hidden = YES;
    }
}
-(void)NaviewHiddenOrShow:(BOOL)hidden
{
    if (hidden==YES) {
        CGRect frame = self.QXnaView.frame;
        frame.origin.y = -64;
        self.QXnaView.frame = frame;
    }
}

 //当表滚动到底部时显示更多
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y >=self.tableView.contentSize.height-432) {
        [self performSelector:@selector(PushToMore) withObject:nil afterDelay:0.5];
    }
}
-(void)PushToMore
{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"XQ" bundle:nil];
    SECViewController *sec = (SECViewController*)[story instantiateViewControllerWithIdentifier:@"detail"];
    [self.navigationController pushViewController:sec animated:YES];
}
//让遮罩隐藏
-(void)removeMask
{
    self.maskView.hidden = YES;
}
//代理方法
-(void)closeDelegate
{
    self.maskView.hidden = YES;
}
-(void)configDelegate
{
    //穿模型，对数据进行归档（还没写）
    //先从文件读取模型
    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:FilePath];
    ShopModel *smodel = [[ShopModel alloc]init];
    smodel.name = _model.name;
    smodel.icon = _model.image[0];
    smodel.oldprice = _model.oldprice;
    smodel.price = _model.price;
    smodel.type = _model.type;
    smodel.count = _model.count;
    smodel.image = _model.image;
    smodel.smallimage = _model.smallimage;
    smodel.pj = _model.pj;
    smodel.detailpj = _model.detailpj;
    smodel.fuwu = _model.fuwu;
    smodel.person=_model.person;
    smodel.flag = YES;
    //归档,先判断当前购物车是否已有此商品，有把原商品的数量增加，没有新建model
    NSMutableArray *muarry = [NSMutableArray arrayWithArray:array];
    int nowtotal = muarry.count;
    if (nowtotal>0) {
        BOOL isHas=NO;
        //判断数组内是否有此商品
        //有的情况
        for(int i=0;i<muarry.count;i++)
        {
            ShopModel *shopmodel2=muarry[i];
            if ([shopmodel2.name isEqualToString:smodel.name]) {
                shopmodel2.count+=smodel.count;
                isHas=YES;
                continue;
            }
        }
        if (isHas==NO)
        {
            [muarry addObject:smodel];
        }

    }
    else
    {
        [muarry addObject:smodel];
    }

       [NSKeyedArchiver archiveRootObject:muarry toFile:FilePath];

    //改变徽章数
    NSArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:FilePath];
    int a =0;
    for (ShopModel *model in array2) {
            a  = a + model.count;
    }
        _huizhang.hidden = NO;
        //改变徽章数
        NSString *str = [NSString stringWithFormat:@"%d",a];
        [_huizhang setTitle:str forState:UIControlStateNormal];
    //关闭确认页面，进入动画
    self.maskView.hidden = YES;
    UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(120, 64, 120, 120)];
    [imgView setImageWithURL:[NSURL URLWithString:_model.image[0]]];
    [self.view addSubview:imgView];
       CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"position";
    animation.fromValue = [NSValue valueWithCGRect:imgView.frame];
    animation.toValue = [NSValue valueWithCGRect:CGRectMake(45, 465,55 , 35)];
    CABasicAnimation *animation1 = [CABasicAnimation animation];
    animation1.keyPath = @"transform.scale";
    animation.fromValue = [NSValue valueWithCGRect:imgView.frame];
    animation1.toValue = @(0.0);
    CAAnimationGroup *group = [[CAAnimationGroup alloc]init];
    group.animations = @[animation,animation1];
    group.duration = 1;
    group.removedOnCompletion = NO;
    group.fillMode = kCAFillModeForwards;
    [imgView.layer addAnimation:group forKey:nil];
    
    //给购物车回樟树
    _main=(DSZMainViewController *)self.tabBarController;
    [_main loadBadgeInShop];
    
   }
- (IBAction)goHomeClick {
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (IBAction)refreshClick {
    [MBProgressHUD showMessage:@""];
    
    [self performSelector:@selector(end) withObject:nil afterDelay:1.5];
}

-(void)end
{
    [MBProgressHUD hideHUD];
    [MBProgressHUD showSuccess:@"刷新成功"];
    self.backGroundVie.hidden = YES;
    self.homeView.hidden = YES;
    self.refreshView.hidden = YES;
    self.shareView.hidden = YES;
    
}
- (IBAction)shareClick {
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"55b8ac0367e58ea260001477"
                                      shareText:@"友盟社会化分享让您快速实现分享等社会化功能，www.umeng.com/social"
                                     shareImage:[UIImage imageNamed:@"psb-2.jpeg"]
                                shareToSnsNames:@[UMShareToSina,UMShareToQzone,UMShareToFacebook]
                                       delegate:self];
}
@end
